package com.itheima.health.security;

import com.itheima.health.pojo.*;
import com.itheima.health.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class SecurityUserDetails implements UserDetailsService {

    @DubboReference
    private UserService userService;
    @DubboReference
    private UserRoleService userRoleService;
    @DubboReference
    private RoleService roleService;
    @DubboReference
    private RolePermissionService rolePermissionService;
    @DubboReference
    private PermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        log.info("[登录-用户配置-前端传值] - name: {}",name);
        User user = userService.findByName(name);
        if (user==null){
            throw new UsernameNotFoundException("您的账号有误请重新输入");
        }
        //创建存入用户角色，权限的容器
        List<GrantedAuthority> authorities = new ArrayList<>();

        List<UserRole> userRoleList = userRoleService.findById(user.getId());
        for (UserRole userRole : userRoleList) {
            Role role = roleService.findById(userRole.getRoleId());
            //存入用户角色
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
            List<RolePermission> rolePermissionList = rolePermissionService.findById(role.getId());
            for (RolePermission rolePermission : rolePermissionList) {
                Permission permission = permissionService.findById(rolePermission.getPermissionId());
                //存入角色对应的权限
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        log.info("[登录-角色&权限] - authorities: {}",authorities);
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
